﻿using System;

using Emgu.CV;
using Emgu.CV.Structure;
using System.Collections.Generic;

namespace iMapa.Backend
{
    public interface ICameraInput
    {
        int getConnectedCamCount();
        int getFps();
        Image<Bgr, Byte> getImage();
        Image<Bgr, Byte> getImage(int camera);
    }
    
    public class CameraInput:ICameraInput, IDisposable
    {
        private static CameraInput current;

        private List<Capture> captures= new List<Capture>();
        private readonly object readlock = new object();
        private int selected;
        private int camcount;

        private CameraInput()
        {
            current = this;
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    captures.Add(new Capture(i));
                    camcount++;
                }

            }
            catch (Exception e)
            {
            }
    
        }

        public static ICameraInput getInstance(){
            if (current == null)
            {
                new CameraInput();
                return current;
            }
            return current;
        }

        public Image<Bgr,Byte> getImage()
        {

            if (captures.Count > selected && captures[selected] != null)
            {
                Image<Bgr, Byte> image = captures[selected].QueryFrame();
                return image != null ? image.Clone() : null;
            }
            else return null;
        }
        public int getFps()
        {
            if (captures.Count > selected && captures[selected] != null)
            {
                double fps = captures[selected].GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FPS);
                return (int) fps;
            }
            else return 0;
        }

        public Image<Bgr, Byte> getImage(int camera)
        {

            if (captures.Count > camera && captures[camera] != null)
            {
                Image<Bgr, Byte> image = captures[selected].QueryFrame();
                return image != null ? image.Clone() : null;
            }
            else return null;
        }

        public void SetSelected(int selected)
        {
            if (selected < captures.Count)
            {
                this.selected = selected;
            }
            else
            {
                selected = 0;
            }
        }

        public void Dispose()
        {
            foreach (Capture c in captures)
            {
                c.Dispose();
            }
            current = null;
        }

        public int getConnectedCamCount()
        {
            return camcount;
        }

        public static void RestartCapture()
        {
            if (current != null)
            {
                current.Dispose();
            }
        }
       
    }
}